﻿using System;
using System.Linq;
using System.Web.Mvc;
using Icms.Core.Model;
using Icms.Core.Service;
using Icms.WebUI.Builder;
using Icms.WebUI.Dto;
using Omu.Awesome.Mvc;

namespace Icms.WebUI.Controllers
{
    public class TemplateController : Cruder<Template, TemplateInput>
    {
        private readonly IPdf p;

        public TemplateController(ICrudService<Template> s, IMapper<Template, TemplateInput> v, IPdf p) : base(s, v)
        {
            this.p = p;
        }

        public virtual ActionResult Search(string search, Guid? parameter, int page = 1, int ps = 5)
        {
            var src = s.Where(o => o.Title.StartsWith(search));
            if (parameter.HasValue) src = src.Where(o => o.TypeId == parameter);

            var rows = this.RenderView("rows", src.OrderBy(u => u.Id).Skip((page - 1) * ps).Take(ps));
            return Json(new { rows, more = src.Count() > page * ps });
        }

        [ValidateInput(false)]
        public override ActionResult Create(TemplateInput o)
        {
            return base.Create(o);
        }

        [ValidateInput(false)]
        public override ActionResult Edit(TemplateInput input)
        {
            return base.Edit(input);
        }

        public ActionResult Pdf(Guid id)
        {
            return p.Make(s.Get(id).Content);
        }
    }
}